package com.dick.weixin.service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

import com.dick.weixin.pojo.WeixinMedia;
import com.dick.weixin.util.CommonUtil;
import com.dick.weixin.util.logging.Logger;
import com.dick.weixin.util.logging.LoggerFactory;

/**
 * 媒体文件上传和下载 类 名 称： WeixinMediaService 类 描 述： 创 建 人： zhangyaomin 邮
 * 箱：zhangyaomin@yunchuangyi.cn 创建时间：2014-3-11下午05:37:23
 */
public class WeixinMediaService {
	private static Logger log = LoggerFactory
			.getLogger(WeixinMediaService.class);

	/**
	 * 上传媒体文件
	 * 
	 * @param accessToken
	 * @param type
	 * @param mediaFileUrl
	 *            媒体文件的URL
	 * @return
	 */
	public static WeixinMedia uploadMedia(String accessToken, String type,
			String mediaFileUrl) {
		WeixinMedia weixinMedia = null;
		String uploadMediaUrl = "http://file.api.weixin.qq.com/cgi-bin/meida/upload?access_token=ACCESS_TOKEN&type=TYPE";
		uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE",
				type);
		// 定义数据分割符
		String boundary = "------------7da2e536604c8";

		try {
			URL uploadUrl = new URL(uploadMediaUrl);
			HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl
					.openConnection();
			uploadConn.setDoOutput(true);
			uploadConn.setDoInput(true);
			uploadConn.setRequestMethod("POST");
			// 设置请求头Content-type
			uploadConn.setRequestProperty("Content-type",
					"multipart/form-data;boundary=" + boundary);
			// 获取媒体文件上传的输出流（往微信服务器写数据）
			OutputStream outputStream = uploadConn.getOutputStream();
			URL mediaUrl = new URL(mediaFileUrl);
			HttpURLConnection mediaConn = (HttpURLConnection) mediaUrl
					.openConnection();
			mediaConn.setDoInput(true);
			mediaConn.setDoOutput(true);
			mediaConn.setRequestMethod("GET");
			// 从请求头中获取内容类型
			String contentType = mediaConn.getHeaderField("Content-Type");
			// 根据内容类型判断文件扩展名
			String fileExt = CommonUtil.getFileExt(contentType);
			// 请求体开始
			outputStream.write(("--" + boundary + "\r\n").getBytes());
			outputStream
					.write(String
							.format(
									"Content-Disposition:form-data;name=\"media\";filename=\"file1%s\"\r\n",
									fileExt).getBytes());
			outputStream.write(String.format("Content-Type:%s\r\n\r\n",
					contentType).getBytes());
			// 获取媒体文件的输入流（读取文件）
			BufferedInputStream bis = new BufferedInputStream(mediaConn
					.getInputStream());
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				// 将媒体文件写到输出流（往微信服务器写数据）
				outputStream.write(buf, 0, size);
			outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
			outputStream.close();
			bis.close();
			mediaConn.disconnect();

			// 获取媒体文件上传的输入流（从微信服务器上读取数据）
			InputStream inputStream = uploadConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null)
				buffer.append(str);
			bufferedReader.close();
			inputStreamReader.close();

			inputStream.close();
			inputStream = null;
			uploadConn.disconnect();

			// 使用JSON-LIB解析返回结果
			JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
			System.out.println(jsonObject);
			weixinMedia = new WeixinMedia();
			weixinMedia.setType(jsonObject.getString("type"));
			if ("thumb".equals(type))
				weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
			else {
				weixinMedia.setMediaId(jsonObject.getString("media_id"));
				weixinMedia.setCreateAt(jsonObject.getInt("created_at"));
			}

		} catch (Exception e) {
			weixinMedia = null;
			log.error("上传媒体文件失败:{}", e);
			e.printStackTrace();
		}

		return weixinMedia;
	}

	public static String getMedia(String accessToken, String mediaId,
			String savePath) {
		String filePath = null;
		String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/meida/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID",
				mediaId);
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("GET");
			if (!savePath.endsWith("/")) {
				savePath += "/";
			}
			String fileExt = CommonUtil.getFileExt(conn
					.getHeaderField("Content-Type"));
			// 將mediaId作为文件名
			filePath = savePath + mediaId + fileExt;
			BufferedInputStream bis = new BufferedInputStream(conn
					.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(filePath));
			byte[] buff = new byte[8096];
			int size = 0;
			while ((size = bis.read(buff)) != -1)
				fos.write(buff, 0, size);
			fos.close();
			bis.close();
			conn.disconnect();
			log.info("下载媒体文件成功,filePath=" + filePath);

		} catch (Exception e) {
			filePath = null;
			log.error("下载媒体文件失败：{}", e);
			e.printStackTrace();
		}
		return filePath;
	}

	public static void main(String[] args) {
		String accessToken = CommonUtil.getToken("appid", "appsecret")
				.getAccessToken();
		// WeixinMedia weixinMedia = uploadMedia(accessToken, "voice",
		// "http://localhost:8080/weixinmpapi/test.mp3");
		// System.out.println(weixinMedia.getMediaId() + "    "
		// + weixinMedia.getType() + "    " + weixinMedia.getCreateAt());

		getMedia(accessToken, "sdfasdfasdfasdfasdf", "/tmp");
	}
}
